<template>
  <view class="ai-tabs">
    <scroll-view :scrollLeft="navScrollLeft" scroll-with-animation :scroll-x="true"
      :class="{'ai-tabs--scrollable': scrollable}">
      <block v-if="needNav">
        <view v-for="(l, idx) in items" class="tabs-item-wrapper" :class="'tabs-item-' + idx" :key="'tab-' + l.value">
          <ai-tab-item :active="activeKey == l.value" :label="l.label" :value="l.value"
            :tab-index="idx"  @click="tabSelected"></ai-tab-item>
        </view>
      </block>
    </scroll-view>

  </view>
</template>

<script>
  export default {
    name: "ai-tabs",
    emits: ["update:activeKey", "change"],
    props: {
      activeKey: String,
      scrollable: {
        type: Boolean,
        default: false
      },
      hideNavIfOnlyOne: {
        type: Boolean,
        default: false
      },
      items: {
        type: Array,
        default: []
      }
    },
    data() {
      return {
        tabsOffsetLeft: 0,
        selectedNavWidth: 0,
        offsetLeftOfCenter: 0,
        navScrollLeft: 0,
      };
    },
    mounted() {

    },
    computed: {
      needNav: {
        get: function() {
          return this.items.length > (this.hideNavIfOnlyOne ? 1 : 0)
        }
      },
      
    },
    methods: {
      tabSelected(e) {
        const { value, tabIndex } = e
        this.selected = value
        this.movePointer(tabIndex)
        this.$emit("update:activeKey", value)
        this.$emit("change", e)
      },
      movePointer(tabIdx) {
        const selectTabClass = `.tabs-item-${tabIdx}`
        const query = uni.createSelectorQuery().in(this)
        query.select(".ai-tabs").boundingClientRect(data => {
          // console.log("offset:", JSON.stringify(data))
          this.tabsOffsetLeft = data.left
        }).exec()
        query.select(selectTabClass).boundingClientRect(data => {
          // console.log("offset:", JSON.stringify(data))
          const tabWidth = data.width
          const tabLeft = data.left
          this.selectedNavWidth = tabWidth
          this.offsetLeftOfCenter = tabLeft + tabWidth / 2
          this.refreshNavPosition(tabIdx)
        }).exec()
      },
      refreshNavPosition(idx) {
        let to = this.offsetLeftOfCenter - this.selectedNavWidth / 2
        this.navScrollLeft = to - this.tabsOffsetLeft
      }
    }
  }
</script>

<style lang="scss">
  @import "@/styles/_var.scss";
  $tabs-nav-margin: 6px;
  $scrollable-width: 6px;


  .ai-tabs-nav {
    position: relative;
    display: flex;
    margin: $tabs-nav-margin 0;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .ai-tabs--scrollable {
    position: relative;
    white-space: nowrap;
    display: flex;
    margin: $tabs-nav-margin 0;
    padding-bottom: $scrollable-width;
    width: 100%;
  }
  
  .tabs-item-wrapper {
    display: inline-block;
  }


</style>